package com.stylefeng.guns.modular.huamao.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.modular.huamao.dao.SktSysConfigsMapper;
import com.stylefeng.guns.modular.huamao.dao.UsersDrawsMapper;
import com.stylefeng.guns.modular.huamao.dao.UsersMapper;
import com.stylefeng.guns.modular.huamao.model.*;
import com.stylefeng.guns.modular.huamao.result.AppResult;
import com.stylefeng.guns.modular.huamao.result.Result;
import com.stylefeng.guns.modular.huamao.service.*;
import com.stylefeng.guns.modular.huamao.util.GetDateUtil;
import com.stylefeng.guns.modular.huamao.util.MSGUtil;
import com.stylefeng.guns.modular.huamao.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.stylefeng.guns.core.base.controller.BaseController;

/**
 * 用户提现控制器
 *
 * @author fengshuonan
 * @Date 2018-04-20 19:02:46
 */
@CrossOrigin()
@RestController
@RequestMapping("/usersDraws")
public class UsersDrawsController extends BaseController {

	private String PREFIX = "/huamao/usersDraws/";

	@Autowired
	private IUsersDrawsService usersDrawsService;
	@Autowired
	UsersDrawsMapper udm;
	@Autowired
	private UsersMapper usersMapper;
	@Autowired
	private IAppSktMaobiChangeService iAppSktMaobiChangeService;
	@Autowired
	private SktSysConfigsMapper sktSysConfigsMapper;
	@Autowired
	private IAccountService accountService;
	@Autowired
	private IAccountShopService accountShopService;
	@Autowired
	private IMessagesService messagesService;
	@Autowired
	private IUsersService usersService;
	@Autowired
	ISktHuamaobtLogService sktHuamaobtLogService;
	@Autowired
	private ISktDateService iSktDateService;
	@Autowired
	private IAppLogKaiyuanService iAppLogKaiyuanService;
	@Autowired
	private IUsersDrawsMaobiService iUsersDrawsMaobiService;
	@Autowired
	private IAppLogCashService iAppLogCashService;
	@Autowired
	private ILogKaiyuanTurnoverService iLogKaiyuanTurnoverService;
	@Autowired
	ISktExchangeUserService exchangeUserService;
	@Autowired
	private IAppUserDrwasService iAppUserDrwasService;
	@Autowired
	private ISktSysConfigsService sktSysConfigsService;

	/**
	 * 跳转到用户提现首页
	 */
	@RequestMapping("")
	public String index() {
		return PREFIX + "usersDraws.html";
	}

	/**
	 * 跳转到添加用户提现
	 */
	@RequestMapping("/usersDraws_add")
	public String usersDrawsAdd() {
		return PREFIX + "usersDraws_add.html";
	}

	/**
	 * 跳转到修改用户提现
	 */
	@RequestMapping("/usersDraws_update/{usersDrawsId}")
	public String usersDrawsUpdate(@PathVariable Integer usersDrawsId, Model model) {
		UsersDraws usersDraws = usersDrawsService.selectById(usersDrawsId);
		model.addAttribute("item", usersDraws);
		return PREFIX + "usersDraws_edit.html";
	}

	/**
	 * 获取用户提现列表
	 */
	@RequestMapping(value = "/list")
	@ResponseBody
	public Object list(UsersDrawsList usersDrawsList) {
		return usersDrawsService.selectUsersDrawsAll(usersDrawsList);
		// return usersDrawsService.selectList(null);
	}

	/**
	 * 新增用户提现
	 */
	@RequestMapping(value = "/add")
	@ResponseBody
	public Object add(UsersDraws usersDraws) {
		usersDrawsService.insert(usersDraws);
		return SUCCESS_TIP;
	}

	/**
	 * 删除用户提现
	 */
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Object delete(@RequestParam Integer usersDrawsId) {
		usersDrawsService.deleteById(usersDrawsId);
		return SUCCESS_TIP;
	}

	/**
	 * 修改用户提现
	 */
	@RequestMapping(value = "/update")
	@ResponseBody
	public Object update(UsersDraws usersDraws) {
		usersDrawsService.updateById(usersDraws);
		return SUCCESS_TIP;
	}

	/**
	 * 用户提现详情
	 */
	@RequestMapping(value = "/detail/{usersDrawsId}")
	@ResponseBody
	public Object detail(@PathVariable("usersDrawsId") Integer usersDrawsId) {
		return usersDrawsService.selectById(usersDrawsId);
	}

	/**
	 * 审核拒绝
	 */
	@RequestMapping("/usersDrawsRefuse")
	public String UsersDrawsRefuse(@RequestParam String drawId, Model model) {
		// 将获取到id存入model为修改做准备
		model.addAttribute("drawId", drawId);
		return PREFIX + "usersDraws_Refuse.html";
	}

	/**
	 * 审核拒绝后的修改数据
	 */
	@RequestMapping("/updateSatus")
	@ResponseBody
	public Object updateSatus(UsersDrawsList usersDrawsList) {
		// 获取操作人员id
		// 将审核状态改为审核拒绝
		usersDrawsList.setCashSatus(-1);
		// 审核时间
		usersDrawsList.setCheckTime(new Date());
		// 设置审核员id
		// 将审核状态改为审核失败
		usersDrawsService.updateSatus(usersDrawsList);
		return SUCCESS_TIP;
	}

	/**
	 * 线下打款
	 */
	@RequestMapping("/usersDrawsMoney")
	@ResponseBody
	public Object usersDrawsMoney(UsersDrawsList usersDrawsList) {
		// 获取操作人员id
		// 将审核状态改为线下打款
		usersDrawsList.setCashSatus(4);
		// 审核时间
		usersDrawsList.setCheckTime(new Date());
		// 设置审核员id
		// 修改审核状态
		usersDrawsService.updateSatus(usersDrawsList);
		return SUCCESS_TIP;
	}
    /**
     * 用户点击赎回
     * @param userId  用户id
     * @param type  赎回类型  1开元宝提现 2现金提现 3开元宝营业额提现
     */
    @RequestMapping("/clickRedeem")
    public Result  clickRedeem(Integer userId,Integer type){
        JSONObject json = usersDrawsService.clickRedeem(userId, type);
        return  Result.OK(json);
    }
	/**
	 * 赎回申请
	 * @param userId  用户ID
	 * @param type  提现的类型：1开元宝提现 2现金提现 3开元宝营业额提现
	 * @param money  提现金额
	 * @param ratio  提现手续费比例 %
	 * @param taxRatio  提现税率比例%  （服务费用）
	 * @param bankCardId  银行卡表ID
	 * @param getTime  提现时间
	 * @param payPwd   支付密码
	 * @return
	 */

	@RequestMapping("/applyRedeem")
	public Result applyRedeem(Integer userId, Integer type, BigDecimal money,  BigDecimal ratio, BigDecimal taxRatio, int bankCardId,Integer getTime,String payPwd){
	//	BigDecimal expenses, BigDecimal expensesrate, BigDecimal taxratio, BigDecimal ratio,String payPwd);
		BigDecimal  expenses=money.multiply(ratio).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);
		BigDecimal ratioMoney = money.multiply(taxRatio).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);
		JSONObject json = usersDrawsService.applyRedeem(userId, type, money, expenses, ratio, taxRatio,ratioMoney,payPwd);
	    return 	Result.OK(json);
	}

	/**
	 * 利率获取
	 * @return
	 */
	@RequestMapping(value = "/ticker")
	@ResponseBody
	public Result ticker (){
		String aaa = sktHuamaobtLogService.ticker().toString();
		return Result.OK(sktHuamaobtLogService.ticker());
	}

	/**
	 * 获取参数
	 * @param userId
	 * @param type
	 * @return
	 */
	@RequestMapping(value = "/getExpenses")
	@ResponseBody
	public Result getExpenses(Integer userId,Integer type){
	//	return Result.EEROR("pc端暂不支持提现，请使用app");
		JSONObject json = new JSONObject();
		Users user = usersMapper.selectById(userId);
		if (user.getUserType()==0){
			return Result.EEROR("普通用户没有申请赎回权限,请升级用户");
		}
		if (type.equals(1)){
			SktSysConfigs sktSysConfigs = new SktSysConfigs();
			sktSysConfigs.setFieldCode("kaiyuanbaoTXt0");
			EntityWrapper<SktSysConfigs> wrapper = new EntityWrapper<SktSysConfigs>(sktSysConfigs);
			sktSysConfigs  = sktSysConfigsService.selectOne(wrapper);
			json.put("expensesrate",sktSysConfigs.getFieldValue());

			SktSysConfigs sktSysConfigs1 = new SktSysConfigs();
			sktSysConfigs1.setFieldCode("taxRatio");
			EntityWrapper<SktSysConfigs> wrapper1 = new EntityWrapper<SktSysConfigs>(sktSysConfigs1);
			sktSysConfigs1  = sktSysConfigsService.selectOne(wrapper1);
			json.put("taxRatio",sktSysConfigs1.getFieldValue());
		}
		if(type.equals(2)){
			if(user.getUserType()==1){
				SktSysConfigs sktSysConfigs = new SktSysConfigs();
				sktSysConfigs.setFieldCode("directorCashDraw");
				EntityWrapper<SktSysConfigs> wrapper = new EntityWrapper<SktSysConfigs>(sktSysConfigs);
				sktSysConfigs  = sktSysConfigsService.selectOne(wrapper);
				json.put("expensesrate",sktSysConfigs.getFieldValue());
				json.put("taxRatio",0);
			}
			if(user.getUserType()==2){
				SktSysConfigs sktSysConfigs = new SktSysConfigs();
				sktSysConfigs.setFieldCode("managerCashDraw");
				EntityWrapper<SktSysConfigs> wrapper = new EntityWrapper<SktSysConfigs>(sktSysConfigs);
				sktSysConfigs  = sktSysConfigsService.selectOne(wrapper);
				json.put("expensesrate",sktSysConfigs.getFieldValue());
				json.put("taxRatio",0);
			}
		}
		if(type.equals(3)){
			SktSysConfigs sktSysConfigs = new SktSysConfigs();
			sktSysConfigs.setFieldCode("kaiyuanYingyeTX");
			EntityWrapper<SktSysConfigs> wrapper = new EntityWrapper<SktSysConfigs>(sktSysConfigs);
			sktSysConfigs  = sktSysConfigsService.selectOne(wrapper);
			json.put("expensesrate",sktSysConfigs.getFieldValue());
			json.put("taxRatio",0);
		}

		return Result.OK(json);
	}

	/**
	 * 赎回申请
	 * @param userId  用户ID
	 * @param type  提现的类型：1开元宝提现 2现金提现 3开元宝营业额提现
	 * @param money  提现金额
	 * @param expenses  手续费+税率（平台扣除的费用）fee
	 * @param expensesrate  提现手续费比例 %   ratio
	 * @param taxRatio  提现税率比例%  （服务费用） 10
	 * @param payPwd   支付密码
	 * @return
	 */
	@RequestMapping(value = "/mbApplyRedeem")
	@ResponseBody
	public Result mbApplyRedeem (Integer userId,BigDecimal moneyRate,Integer type, BigDecimal money, BigDecimal expenses, BigDecimal expensesrate, BigDecimal taxRatio, BigDecimal ratio, String payPwd) throws Exception{
		JSONObject json = new JSONObject();
		return Result.EEROR("pc端暂不支持提现，请使用app");
//		return Result.EEROR("该功能暂时关闭");
//		Users user = usersMapper.selectById(userId);
//		if (user.getUserType()==0){
//			return Result.EEROR("普通用户没有申请赎回权限,请升级用户");
//		}
//		if (user.getIsWithdrawCash()!=1){
//			return Result.EEROR("您没有申请赎回权限");
//		}
//		int isOperation=user.getIsOperation();
//		if (isOperation==0){
//			return Result.EEROR("该功能已关闭！");
//		}
//		SimpleDateFormat setTime = new SimpleDateFormat("HH:mm:ss");
//		String parse = setTime.format(new Date());
//		Date parse1 = setTime.parse(parse);//当前时间时分秒
//		Date parse2 = setTime.parse("11:00:00");//设定11点时间
//		if (parse2.getTime()>parse1.getTime()){//如果设定时分秒大于当前时分秒
//			return Result.EEROR("猫币赎回在11点开启");
//		}
//		//判定今天是否为工作日
//		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
//		String format1 = format.format(new Date());
//		int date = Integer.parseInt(format1);
//
//		SktDate sktDate=iSktDateService.selectDateByDate(date);
//		if (sktDate.getStatus()!=0){
//			if (sktDate.getStatus()==1){
//				return Result.EEROR("今日为休息日不可进行提现操作");
//			}
//			SktSysConfigs sktSysConfigs = sktSysConfigsMapper.selectSysConfigsByFieldCode("isHolidaysCash");
//			if (Integer.parseInt(sktSysConfigs.getFieldValue())!=1){
//				return Result.EEROR("今日不可进行提现操作");
//			}
//		}
//
//		//SktSysConfigs sktSysConfigs = sktSysConfigsMapper.selectSysConfigsByFieldCode("drawsAmountDay");
//		//Integer fieldValue = Integer.parseInt(sktSysConfigs.getFieldValue());
//		BigDecimal moneyValue=money;
//		JSONObject jsonObject = usersService.checkPayPassWorld(userId, payPwd);
//		if ("00".equals(jsonObject.get("code"))){
//			return Result.EEROR("交易密码不正确");
//		}
//		if (!MSGUtil.isBlank(user.getPrivilegeTime())) {
//			long nextThreeMonth = GetDateUtil.getNextAnyMonth(3,user.getPrivilegeTime()).getTime();
//			long privilegeTime = new Date().getTime();
//			if(nextThreeMonth>privilegeTime){
//				return Result.EEROR("特权账号三个月内不能提现！");
//			}
//		}
//		//获取用户账户信息
//		Account account = accountService.selectAccountByuserId(userId);
//		//获取商家账户信息
//		AccountShop accountShop=accountShopService.selectAccountShopByUserId(userId);
//		//校验赎回人状态
//		if (MSGUtil.isBlank(user.getTrueName())){
//			return Result.EEROR("您还未实名！");
//		}
//		SktSysConfigs drawsAmountMin = sktSysConfigsMapper.selectSysConfigsByFieldCode("drawsAmountMin");
//		SktSysConfigs drawsAmountMax = sktSysConfigsMapper.selectSysConfigsByFieldCode("drawsAmountMax");
//		Double min=Double.valueOf(drawsAmountMin.getFieldValue());
//		Double max=Double.valueOf(drawsAmountMax.getFieldValue());
//		//校验计算手续费
//		BigDecimal feeMoney = money.multiply(expensesrate).multiply(new BigDecimal(0.01)).setScale(2,BigDecimal.ROUND_HALF_UP);
//		BigDecimal ratioMoney = money.multiply(taxRatio).multiply(new BigDecimal(0.01)).setScale(2,BigDecimal.ROUND_HALF_UP);
//		if (type==2){
//			ratioMoney=new BigDecimal(0);
//		}
//		if (type==3){
//			ratioMoney=new BigDecimal(0);
//		}
//		if (money.doubleValue()<min){
//			return Result.EEROR("单笔最小赎回额度为:"+min.toString());
//		}
//		if (money.doubleValue()>max){
//			return Result.EEROR("单笔最大赎回额度为:"+max.toString());
//		}
//		BigDecimal allFee = feeMoney.add(ratioMoney).setScale(3,BigDecimal.ROUND_UP);//手续费+综合服务费(总手续费)
//        /*System.out.println(feeMoney+"____________________________");
//        System.out.println(expenses+"______________________________");
//        int compare = feeMoney.compareTo(expenses);
//        if (compare!=0){
//            return AppResult.ERROR("手续费计算有误！",-1);
//        }
//        if (ratioMoney.compareTo(ratio)!=0){
//            return AppResult.ERROR("交综合服务费金额计算有误！",-1);
//        }*/
//		Date dayBegin = GetDateUtil.getDayBegin();
//		Date dayEnd = GetDateUtil.getDayEnd();
//		Map<String, Object> map = new HashMap<>();
//		map.put("startTime",dayBegin);
//		map.put("endTime",dayEnd);
//		map.put("userId",userId);
//		UsersDrawsMaobi sumMoney=iUsersDrawsMaobiService.selectSumMoneyByUserId(map);
//		BigDecimal dayHandle=new BigDecimal(0.00);
//		if (!MSGUtil.isBlank(sumMoney)){
//			dayHandle= sumMoney.getMoney();
//		}
//		String tCode="drawsAmountDay";
//		if(type==1){
//			tCode="drawsKaiyuan";
//		}
//		if (type==3){
//			tCode="drawsKaiyuanTrunover";
//		}
//		SktSysConfigs drawsAmountDays = sktSysConfigsMapper.selectSysConfigsByFieldCode(tCode);
//		BigDecimal drawsAmountDay = new BigDecimal(drawsAmountDays.getFieldValue());
//		BigDecimal biggest = dayHandle.add(money);
//		if (drawsAmountDay.compareTo(biggest)==-1){
//			return Result.EEROR("每日最大赎回额度为:"+drawsAmountDay+",本日还可提现"+drawsAmountDay.subtract(dayHandle));
//		}
////		SktSysConfigs drawsAmountDays = sktSysConfigsMapper.selectSysConfigsByFieldCode("drawsAmountDay");
////		BigDecimal drawsAmountDay = new BigDecimal(drawsAmountDays.getFieldValue());
////		BigDecimal biggest = dayHandle.add(money);
////		if (drawsAmountDay.compareTo(biggest)==-1){
////			return Result.EEROR("每日最大赎回额度为:"+drawsAmountDay+",本日还可提现"+drawsAmountDay.subtract(dayHandle));
////		}
//		//根据不同赎回类型判断对应余额是否足够 $param['type']  1华宝赎回 2现金赎回 3华宝营业额赎回
//		BigDecimal countMoney=money;
//		BigDecimal currentMoney=new BigDecimal(0);
//		if (type==1){
//			if ((money.divideAndRemainder(BigDecimal.valueOf(100))[1]).compareTo(BigDecimal.valueOf(0))!=0){
//				return Result.EEROR("华宝赎回所得金额必须为100的倍数！");
//			}
//			if (account.getKaiyuan().compareTo(countMoney.multiply(BigDecimal.valueOf(100)))==-1){
//				return Result.EEROR("华宝余额不足！");
//			}
//			currentMoney=account.getKaiyuan();
//		}
//		if (type==2){
//			if (account.getCash().compareTo(countMoney)==-1){
//				return Result.EEROR("现金余额不足！");
//			}
//			currentMoney=account.getCash();
//		}
//		if (type==3){
//			if(accountShop.getKaiyuanTurnover().compareTo(countMoney.multiply(BigDecimal.valueOf(100)))==-1){
//				return Result.EEROR("华宝营业额余额不足！");
//			}
//			currentMoney=accountShop.getKaiyuanTurnover();
//		}
//
//		//计算 赎回基本业务逻辑处理
//		String orderNo = StringUtils.getOrderIdByTime("F");
//		Map<String, Object> result = this.draw(userId, money, moneyRate, type, expensesrate, taxRatio, allFee, orderNo, currentMoney,ratio);
//		int status = Integer.parseInt(result.get("status").toString());
//		if (status==1){
//			return Result.OK("赎回申请操作成功！");
//		}
//		return Result.EEROR(result.get("msg").toString());
	}

	/**
	 * 赎回   计算 赎回基本业务逻辑处理
	 * @param type $uid 用户ID
	 * @param type $money 赎回金额
	 * @param type $type 赎回类型
	 * @param type $expensesrate 手续费比例
	 * @param type $taxRatio 综合服务费比例
	 * @param type $allFee 手续费加综合服务费
	 * @param type $bankCardId 用户赎回卡ID
	 * @param type $orderNo 订单号
	 * @param type $currentMoney 当前额度
	 * @return boolean
	 */
	public Map<String,Object> draw(Integer userId, BigDecimal money, BigDecimal moneyRate, Integer type, BigDecimal expensesrate, BigDecimal taxRatio, BigDecimal allFee, String orderNo, BigDecimal currentMoney, BigDecimal ratio) {
		Map<String, Object> result = new HashMap<>();
		try {
			if (money.compareTo(BigDecimal.valueOf(0))==-1){
				result.put("msg","金额不能为0");
				result.put("status",-1);
				return result;
			}
			BigDecimal allmoney=money;//需要从余额扣除的金额
			BigDecimal hasmoney=money.subtract(allFee);//预计得到金额
			Date time = new Date();
			//赎回记录
			UsersDrawsMaobi usersDrawsMaobi = new UsersDrawsMaobi();
			usersDrawsMaobi.setDrawNo(orderNo);
			usersDrawsMaobi.setUserId(userId);
			usersDrawsMaobi.setType(type);
			usersDrawsMaobi.setMoney(hasmoney);
			BigDecimal amount = hasmoney.multiply(moneyRate).setScale(4, BigDecimal.ROUND_DOWN);
			usersDrawsMaobi.setMaobi(amount);
			usersDrawsMaobi.setCheckRemark("转化猫币成功");
			/**********************************************对接交易所开始***************************************/
			int cashSatus=1;
			Map<String, Object> recharge = iAppSktMaobiChangeService.recharge(userId, currentMoney,amount, orderNo,moneyRate,money,1);
			Integer status = Integer.parseInt(recharge.get("status").toString());
			if (status==-2){
				result.put("msg","该用户未注册交易所账户");
				result.put("status",-1);
				return result;
			}
			if(status!=1){
				usersDrawsMaobi.setCheckRemark("交易所转化失败");
				cashSatus=0;
			}
			//转为猫币的状态
			/**********************************************对接交易所结束***************************************/
			usersDrawsMaobi.setFee(allFee);
			usersDrawsMaobi.setRatio(expensesrate);
			usersDrawsMaobi.setTaxratio(taxRatio);
			usersDrawsMaobi.setCashSatus(cashSatus);
			usersDrawsMaobi.setCreateTime(new Date());
			UsersDraws usersDraws = new UsersDraws();
			usersDraws.setDrawNo(orderNo);
			usersDraws.setBankCardId(0);
			usersDraws.setUserId(userId);
			usersDraws.setType(type);
			usersDraws.setMoney(hasmoney);
			usersDraws.setFee(allFee);
			usersDraws.setRatio(ratio);
			usersDraws.setTaxratio(taxRatio);
			usersDraws.setCashSatus(3);
			usersDraws.setCreateTime(new Date());
			usersDraws.setSpecialType(0);
			if (status!=1){
				result.put("msg","交易所转化失败");
				result.put("status",-1);
				return result;
			}
			if (type==1){//华宝
				//扣除因赎回减少的现金、华宝、华宝营业额额度
				Map<String, Object> kaiYuanMap = new HashMap<>();
				kaiYuanMap.put("userId",userId);
				kaiYuanMap.put("allmoney",allmoney.multiply(BigDecimal.valueOf(100)));
				kaiYuanMap.put("kaiyuan","kaiyuan");
				boolean b = accountService.uptateKaiyuanByUserId(kaiYuanMap);
				if (!b){
					result.put("msg","转化失败");
					result.put("status",-1);
					return result;
				}
				if (allFee.compareTo(BigDecimal.valueOf(0))==1){
					//华宝赎回流水
					LogKaiyuan logKaiyuan = new LogKaiyuan();
					logKaiyuan.setType(41);
					logKaiyuan.setFromId(0);
					logKaiyuan.setUserId(userId);
					logKaiyuan.setOrderNo(orderNo);
					logKaiyuan.setPreKaiyuan(currentMoney);
					logKaiyuan.setKaiyuanType(-1);
					logKaiyuan.setKaiyuan(hasmoney);
					logKaiyuan.setRemark("赎回支出猫币");
					logKaiyuan.setDataFlag(1);
					logKaiyuan.setCreateTime(new Date());
					boolean insert = iAppLogKaiyuanService.insert(logKaiyuan);
					//华宝赎回手续费流水
					logKaiyuan=new LogKaiyuan();
					logKaiyuan.setType(34);
					logKaiyuan.setFromId(0);
					logKaiyuan.setUserId(userId);
					logKaiyuan.setOrderNo(orderNo);
					logKaiyuan.setPreKaiyuan(currentMoney.subtract(hasmoney.multiply(BigDecimal.valueOf(100))));
					logKaiyuan.setKaiyuanType(-1);
					logKaiyuan.setKaiyuan(allFee);
					logKaiyuan.setRemark("赎回支出手续费+综合服务费");
					logKaiyuan.setDataFlag(1);
					logKaiyuan.setCreateTime(new Date());
					boolean inserts = iAppLogKaiyuanService.insert(logKaiyuan);
				}
			}
			if (type==2){//现金
				//扣除因赎回减少的现金、华宝、华宝营业额额度
				Map<String, Object> cashMap = new HashMap<>();
				cashMap.put("userId",userId);
				cashMap.put("allmoney",allmoney);
				cashMap.put("cash","cash");
				boolean b = accountService.uptateCashByUserId(cashMap);
				if (!b){
					result.put("msg","转化失败");
					result.put("status",-1);
					return result;
				}
				if (allFee.compareTo(BigDecimal.valueOf(0))==1){
					//现金赎回流水
					LogCash logCash = new LogCash();
					logCash.setType(39);
					logCash.setFromId(0);
					logCash.setUserId(userId);
					logCash.setOrderNo(orderNo);
					logCash.setPreCash(currentMoney);
					logCash.setCashType(-1);
					logCash.setCash(hasmoney);
					logCash.setRemark("赎回支出猫币");
					logCash.setDataFlag(1);
					logCash.setCreateTime(new Date());
					boolean insert = iAppLogCashService.insert(logCash);
					//现金赎回手续费流水
					logCash=new LogCash();
					logCash.setType(36);
					logCash.setFromId(0);
					logCash.setUserId(userId);
					logCash.setOrderNo(orderNo);
					logCash.setPreCash(currentMoney.subtract(hasmoney));
					logCash.setCashType(-1);
					logCash.setCash(allFee);
					logCash.setRemark("赎回支出手续费");
					logCash.setDataFlag(1);
					logCash.setCreateTime(new Date());
					boolean inserts = iAppLogCashService.insert(logCash);
				}
			}
			if (type==3){//华宝营业额
				//扣除因赎回减少的现金、华宝、华宝营业额额度
				Map<String, Object> map = new HashMap<>();
				map.put("userId",userId);
				map.put("allmoney",allmoney.multiply(BigDecimal.valueOf(100)));
				boolean b=accountShopService.updateKaiyuanTurnoverByUserId(map);
				if (!b){
					result.put("msg","转化失败");
					result.put("status",-1);
					return result;
				}
				if (allFee.compareTo(BigDecimal.valueOf(0))==1){
					//华宝营业额赎回流水
					LogKaiyuanTurnover logKaiyuanTurnover = new LogKaiyuanTurnover();
					logKaiyuanTurnover.setType(41);
					logKaiyuanTurnover.setFromId(0);
					logKaiyuanTurnover.setUserId(userId);
					logKaiyuanTurnover.setOrderNo(orderNo);
					logKaiyuanTurnover.setPreKaiyuan(currentMoney);
					logKaiyuanTurnover.setKaiyuanType(-1);
					logKaiyuanTurnover.setKaiyuan(hasmoney);
					logKaiyuanTurnover.setRemark("赎回支出猫币");
					logKaiyuanTurnover.setDataFlag(1);
					logKaiyuanTurnover.setCreateTime(new Date());
					boolean insert = iLogKaiyuanTurnoverService.insert(logKaiyuanTurnover);
					//华宝营业额赎回手续费流水
					logKaiyuanTurnover=new LogKaiyuanTurnover();
					logKaiyuanTurnover.setType(34);
					logKaiyuanTurnover.setFromId(0);
					logKaiyuanTurnover.setUserId(userId);
					logKaiyuanTurnover.setOrderNo(orderNo);
					logKaiyuanTurnover.setPreKaiyuan(currentMoney.subtract(hasmoney.multiply(BigDecimal.valueOf(100))));
					logKaiyuanTurnover.setKaiyuanType(-1);
					logKaiyuanTurnover.setKaiyuan(allFee);
					logKaiyuanTurnover.setRemark("赎回支出手续费");
					logKaiyuanTurnover.setDataFlag(1);
					logKaiyuanTurnover.setCreateTime(new Date());
					boolean inserts = iLogKaiyuanTurnoverService.insert(logKaiyuanTurnover);
				}
			}
			//插入现金账户记录表
			iAppUserDrwasService.insert(usersDraws);
			//插入赎回记录表
			iUsersDrawsMaobiService.insert(usersDrawsMaobi);
			result.put("msg","转化成功");
			result.put("status",1);
			return result;
		}catch (Exception e){
			e.printStackTrace();
			throw new RuntimeException("失败");
		}
	}

	/*----------------------------------------pc端提现HHTB操作----------------------------------------*/

	/**
	 * 提现(数据回显HHTB)
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/hhtbDraw")
	@ResponseBody
	public Result hhtbDraw(Integer userId){
		JSONObject jsonObject = iAppUserDrwasService.cashDrawHHTB(userId);
		return Result.OK(jsonObject);
	}
	@RequestMapping(value = "/hhtbHandling")
	@ResponseBody
	public Result hhtbHandling(Integer userId,
							   String payPwd,
							   BigDecimal moneyRate,
							   BigDecimal money,
							   BigDecimal expenses,
							   BigDecimal expensesrate,
							   Integer type,
							   BigDecimal ratio,
							   BigDecimal taxRatio){
		try {
			AppResult json = iAppUserDrwasService.applyRedeemHHTB(userId,moneyRate, type, money, expenses, expensesrate, taxRatio, ratio,payPwd);
			json.getData();
			return Result.OK(json.getData());
		}catch (Exception e){
			e.printStackTrace();
			throw new RuntimeException("失败");
		}


	}

}
